class Time

  def self.from_options(options)
    self.local(options[:year].to_i, options[:month].to_i, options[:day].to_i)
  end

  def self.from_extended_options(options)
    options.each { |k,v| options[k.to_sym] = v }
    if options[:month_year]
      options[:month] = options[:month_year].split('-').first.strip
      options[:year] = options[:month_year].split('-')[1].strip
    end
    self.local(options[:year].to_i, options[:month].to_i, options[:day].to_i, options[:hour].to_i, options[:minute].to_i, 0)
  end

  def long
    self.strftime("%d %B %Y, %H:%M")       # 12 noviembre de 2007, 12:54
  end

  def long_no_time
    self.strftime("%d de %B %Y")           # 12 de noviembre de 2007
  end

  def short
    self.strftime("%d %b %Y")              # 12 nov 2007
  end

  def time
    self.strftime("%H:%M")                 # 12:54
  end

  def microformat
    self.strftime("%Y-%m-%dT%H:%M:%S+01:00")  # 2007-02-01T09:25:11+01:00
                                              # Zona horaria metida a pelo!
  end

  def monthname
    Date::MONTHNAMES[self.mon]                # Noviembre
  end

  def month_year
    self.strftime("%B %Y")                    # Noviembre 2007
  end

  alias :strftime_nolocale :strftime

  def strftime(format)
    format = format.dup
    format.gsub!(/%a/, Date::ABBR_DAYNAMES[self.wday])
    format.gsub!(/%A/, Date::DAYNAMES[self.wday])
    format.gsub!(/%b/, Date::ABBR_MONTHNAMES[self.mon])
    format.gsub!(/%B/, Date::MONTHNAMES[self.mon])
    self.strftime_nolocale(format)
  end

  def params_for_url
    {:year => year, :month => month, :day => day}
  end

end


class Date

  remove_const(:MONTHNAMES)
  MONTHNAMES = [ nil,
    'Enero',
    'Febrero',
    'Marzo',
    'Abril',
    'Mayo',
    'Junio',
    'Julio',
    'Agosto',
    'Septiembre',
    'Octubre',
    'Noviembre',
    'Diciembre'
  ]
  remove_const(:DAYNAMES)
  DAYNAMES = [
    'Domingo',
    'Lunes',
    'Martes',
    'Miércoles',
    'Jueves',
    'Viernes',
    'Sábado'
  ]
  remove_const(:ABBR_MONTHNAMES)
  remove_const(:ABBR_DAYNAMES)
  ABBR_MONTHNAMES = MONTHNAMES.map {|month| ( month ? month.chars[0..2] : nil)}
  ABBR_DAYNAMES =     DAYNAMES.map {|month| ( month ? month.chars[0..2] : nil)}

  def ABBR_MONTHNAMES.for_select
    map_with_index {|name, i| [name, i]}.reject {|i| i.first.nil?}
  end

  def self.abbr_days
    abbr = []
    DAYNAMES.each do |day|
      next if day == DAYNAMES.first
      abbr << ( day ? day.chars[0...1] : nil)
    end
    first = DAYNAMES.first
    abbr << (first ? first.chars[0...1] : nil)
    abbr
  end

  def short
    self.strftime("%d %b %Y")                 # 12 nov 2007
  end

end
